package cn.kgc.vue.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/4/10
 * @description jwt工具类  创建  校验 解析token
 */
@Component
public class JWTUtil {

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.timeOut}")
    private Integer timeOut;
    private HashMap<String, Object> header = new HashMap<>();

    public JWTUtil() {
        header.put("alg", "HS256");
        header.put("typ", "JWT");
    }

    // 生成token
    public String createToken(HashMap<String, Object> payload) {

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, 7);

        return JWT.create()
                .withHeader(header)
                .withClaim("user", payload)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));
    }

    // 解析token
    public Map<String, Object> getClaims(String token) {

        return JWT.decode(token).getClaim("user")
                .asMap();
    }

    // 校验token
    public Boolean verify(String token) {

        JWT.require(Algorithm.HMAC256(secret)).build()
                .verify(token);

        return true;
    }


}
